<template>
  <div class="map-body" style="width: 100%;height:100%;position: absolute;">
    <div id="trackre-map" class="map" style="width: 100%;height:100%;position: absolute;"></div>
    <div class="map-time">
      <!-- <el-form ref="form" size="mini" label-width="60px">
            <el-form-item label="请选择">
                <el-date-picker
                    style='width:100%'
                    v-model="dateForm"
                      range-separator="至"
                    type="datetimerange"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    @change='onSearchTrip'
                >
                </el-date-picker>
            </el-form-item>
             <el-form-item>
                <el-button type="primary" @click="onSearchTrip">确定</el-button>
            </el-form-item>
      </el-form>-->
      <div class="block">
        <el-date-picker
          v-model="timeValue"
          type="datetimerange"
          :picker-options="pickerOptions2"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          align="right"
        ></el-date-picker>
        <el-button type="primary" @click="getLine()">回放轨迹</el-button>
      </div>
      <div class="paly-btn">
        <el-button type="primary" @click="pauseLushu()">暂停</el-button>
        <el-button type="primary" @click="runLushu()">开始</el-button>
        <el-button type="primary" @click="stopLushu()">终止</el-button>
        <el-button type="primary" @click="fastSpeech()">加速</el-button>
        <el-button type="primary" @click="slowSpeech()">减速</el-button>
      </div>
    </div>
  </div>
</template>
 
<script>
import moment from "moment";
import BMap from "BMap";
import BMapLib from "BMapLib";
// const { BMap, BMapLib } = window;

export default {
  props: {
    deviceId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      map: null,
      interval: null,
      vcu: "",
      timeValue: ["2015-11-25 14:00:00", "2015-11-25 16:00:00"], //时间
      pickerOptions2: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            }
          }
        ]
      },
      points: [],
      id: "",
      lushu: null,
      speed: 1500, //速度
      speedbase: 200 //速度加减基数
    };
  },
  beforeDestroy() {
    clearInterval(this.interval);
  },
  methods: {
    // init map

    initTrackreBaiduMap: function() {
      var map = new BMap.Map("trackre-map", { enableMapClick: false });
      map.centerAndZoom(new BMap.Point(114.088142, 32.180034), 10);
      map.enableScrollWheelZoom();
      map.disableDoubleClickZoom(); //禁止双击缩放
      map.enableScrollWheelZoom(true);
      //this.addDistrict("信阳");
      //渲染个性化百度地图
      addindividuation(map);

      window.trackreBaiduMap = map; //将map变量储存在全局
    },
    init(points) {
      let map = window.trackreBaiduMap;
      map.enableScrollWheelZoom(true);
      let arrPois = [];
      let length = points.length >> 1;
      var _this = this;

      let carImg = "static/img/icon_drivce_small.png";
      let startImg = "static/img/start.png";
      let endImg = "static/img/end.png";

      // points.forEach(poi => {
      //   arrPois.push(new BMap.Point(poi.lng, poi.lat));
      // });

      for (var i = 0; i < points.length; i++) {
        arrPois.push(new BMap.Point(points[i].lng, points[i].lat));
      }

      map.centerAndZoom();
      map.setViewport(arrPois);
      let marker1 = new BMap.Marker(arrPois[0], {
        icon: new BMap.Icon(startImg, new BMap.Size(64, 64), {
          imageOffset: new BMap.Size(15, 0) //图片的偏移量。为了是图片底部中心对准坐标点。
        })
      });
      let marker2 = new BMap.Marker(arrPois[points.length - 1], {
        icon: new BMap.Icon(endImg, new BMap.Size(64, 64), {
          imageOffset: new BMap.Size(15, 0) //图片的偏移量。为了是图片底部中心对准坐标点。
        })
      });
      // var label = new BMap.Label("粤A30780", { offset: new BMap.Size(0, -30) });
      // label.setStyle({
      //   border: "1px solid rgb(204, 204, 204)",
      //   color: "rgb(0, 0, 0)",
      //   borderRadius: "10px",
      //   padding: "5px",
      //   background: "rgb(255, 255, 255)"
      // });
      // marker.setLabel(label);

      map.addOverlay(marker1);

      BMapLib.LuShu.prototype._move = function(initPos, targetPos, effect) {
        var pointsArr = [initPos, targetPos]; //点数组
        var me = this,
          //当前的帧数
          currentCount = 0,
          //步长，米/秒
          timer = 10,
          step = this._opts.speed / (1000 / timer),
          //初始坐标
          init_pos = this._projection.lngLatToPoint(initPos),
          //获取结束点的(x,y)坐标
          target_pos = this._projection.lngLatToPoint(targetPos),
          //总的步长
          count = Math.round(me._getDistance(init_pos, target_pos) / step);
        //显示折线 syj201607191107

        this._map.addOverlay(
          new BMap.Polyline(pointsArr, {
            strokeColor: "#5298ff",
            strokeWeight: 5,
            strokeOpacity: 0.5
          })
        ); // 画线
        //如果小于1直接移动到下一点
        if (count < 1) {
          me._moveNext(++me.i);
          return;
        }
        me._intervalFlag = setInterval(function() {
          //两点之间当前帧数大于总帧数的时候，则说明已经完成移动
          if (currentCount >= count) {
            clearInterval(me._intervalFlag);
            //移动的点已经超过总的长度
            if (me.i > me._path.length) {
              map.addOverlay(marker2);
              return;
            }
            //运行下一个点
            me._moveNext(++me.i);
          } else {
            currentCount++;
            var x = effect(init_pos.x, target_pos.x, currentCount, count),
              y = effect(init_pos.y, target_pos.y, currentCount, count),
              pos = me._projection.pointToLngLat(new BMap.Pixel(x, y));
            //设置marker
            if (currentCount == 1) {
              var proPos = null;
              if (me.i - 1 >= 0) {
                proPos = me._path[me.i - 1];
              }
              if (me._opts.enableRotation == true) {
                me.setRotation(proPos, initPos, targetPos);
              }
              if (me._opts.autoView) {
                if (!me._map.getBounds().containsPoint(pos)) {
                  me._map.setCenter(pos);
                }
              }
            }
            //正在移动
            me._marker.setPosition(pos);
            //设置自定义overlay的位置
            me._setInfoWin(pos);
          }
        }, timer);
      };
      //  this.drawLine(arrPois)
      _this.lushu = new BMapLib.LuShu(map, arrPois, {
        autoView: true, //是否开启自动视野调整，如果开启那么路书在运动过程中会根据视野自动调整
        icon: new BMap.Icon(carImg, new BMap.Size(64, 64), {
          imageOffset: new BMap.Size(0, 5) //图片的偏移量。为了是图片底部中心对准坐标点。
        }),
        speed: _this.speed,
        enableRotation: true,
        landmarkPois: [] //是否设置marker随着道路的走向进行旋转
      });

      _this.lushu.start();
    },
    // 划线
    drawLine(arr) {
      const lineOP = {
        strokeColor: "blue",
        strokeWeight: 1,
        strokeOpacity: 0.5
      };
      const polyline = new BMap.Polyline(arr, lineOP);
      this.map.addOverlay(polyline);
    },
    // 定时调用划线
    startDraw(arr) {
      this.map.setViewport(arr);
      let i = 2;
      const len = arr.length;
      this.interval = setInterval(() => {
        const points = [...arr];
        points.length = i;
        i++;
        this.drawLine(points);
        if (i === len) {
          clearInterval(this.interval);
        }
      }, 500);
    },
    getLine(startTime, endTime) {
      const loading = this.$loading({
        lock: true,
        text: "正在加载..."
      });
      let query = {
        startTime: startTime || moment(0, "HH").unix() * 1000,
        endTime: endTime || moment({ hour: 23, minute: 59 }).unix() * 1000,
        vcuNo: this.vcu
      };
      let that = this;

      this.getJSON(
        "http://47.106.68.29:9999/bmap/getTrajectory?id=" + this.deviceId
      ) // => 这里面是就try
        .catch(error => {
          console.log("请求失败"); // => 这里就是catch到了error，如果处理error以及返还合适的值
          loading.close();
        })
        .then(value => {
          console.log("请求成功");
          if (value.length == 0) {
            that.$alert("该车辆当天时间段内没有行程", "提示", {
              confirmButtonText: "确定"
            });
          } else {
            console.log("初始化开始请求");

            that.init(JSON.parse(value));
          }
          loading.close();
        });
    },
    setvalidDate(value) {
      return new Date(value) > new Date();
    },

    // 搜索
    onSearchTrip() {
      let {
        day,
        time: [startTime, endTime]
      } = this.form;

      console.log(
        this.getTimestamp(day, startTime),
        this.getTimestamp(day, endTime)
      );
      this.getLine(
        this.getTimestamp(day, startTime),
        this.getTimestamp(day, endTime)
      );
    },
    getTimestamp(day, time) {
      let date =
        moment(new Date(day)).format("YYYY-MM-DD") +
        " " +
        moment(new Date(time)).format("HH:mm:ss");
      return new Date(date).getTime();
    },

    // 追踪 设备号信息
    getTrajectory: function(id) {
      console.log("请求数据开始");
      var _this = this;
      var _window = window;
      var pois = [];
      $.ajax({
        url: "http://47.106.68.29:9999/bmap/getTrajectory", //请求的url地址
        dataType: "json", //返回格式为json
        data: { id: id }, //参数值
        type: "GET", //请求方式
        async: false,
        beforeSend: function() {
          //请求前的处理
        },
        success: function(req) {
          _this.points = req;
          return Promise.resolve(req);
        },
        complete: function() {
          //请求完成的处理
          console.log("完成");
        },
        error: function() {
          //请求出错处理
          console.log("失败");
        }
      });
    },

    getJSON: function(url) {
      return new Promise((resolve, reject) => {
        var xhr = new XMLHttpRequest();
        xhr.open("GET", url, true);

        xhr.onreadystatechange = function() {
          if (this.readyState === 4) {
            if (this.status === 200) {
              resolve(this.responseText, this);
            } else {
              var resJson = { code: this.status, response: this.response };
              reject(resJson, this);
            }
          }
        };

        xhr.send();
      });
    },
    runLushu: function() {
      this.lushu.start();
    },
    stopLushu() {
      this.lushu.stop();
      window.trackreBaiduMap.clearOverlays();
    },
    pauseLushu() {
      this.lushu.pause();
    },
    fastSpeech: function() {
      this.lushu._opts.speed = this.lushu._opts.speed + this.speedbase;
    },
    slowSpeech: function() {
      if (this.speed > this.speedbase) {
        this.lushu._opts.speed = this.lushu._opts.speed - this.speedbase;
      }
    }
  },
  mounted() {
    this.initTrackreBaiduMap();
    // this.vcu = this.$route.params.vcu;
    //this.getLine();
  }
};
</script>
<style scoped>

.map-body {
  position: relative;
}
.map-time {
  position: absolute;
  top: 0;
  left: 0;
  background-color: rgba(6, 21, 33, 0.9);
  padding: 15px;
  border-radius: 0 0 10px 0;
}
.line {
  text-align: center;
}
.map {
  width: 100%;
  min-height: 600px;
  min-height: 90vh;
  background-color: #999;
}
.btn-sure {
  text-align: right;
}
.map-time .el-button--primary {
  background: #00a5ff;
  border-radius: 100px;
}
.map-time .el-input__inner {
  background: #041929;
  border: 1px solid #0b272d;
  border-radius: 100px;
}
.paly-btn {
  padding: 20px 0;
}

</style>
